from appium.webdriver.common.appiumby import AppiumBy
from selenium.common import NoSuchElementException

from 水质.utils.Logger import logger
import time
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC


def find_child_elements(els):
    child_elements = els.find_elements(AppiumBy.XPATH, ".//*")
    return child_elements


def allowPermission(driver):
    try:
        el_allow = driver.find_element(by=AppiumBy.XPATH, value='//*[@text="允许"]')
        el_allow.click()
        logger.log("点击允许")
    except NoSuchElementException:
        try:
            el_allow = driver.find_element(by=AppiumBy.XPATH, value='//*[@text="始终允许"]')
            el_allow.click()
            logger.log("点击始终允许")
        except NoSuchElementException:
            try:
                el_allow = driver.find_element(by=AppiumBy.XPATH, value='//*[@text="仅在使用中允许"]')
                el_allow.click()
                logger.log("仅在使用中允许")
            except NoSuchElementException:
                pass


def wait_Id(driver, id):
    el = WebDriverWait(driver, 10).until(EC.visibility_of_element_located((AppiumBy.ID, id)))
    return el


def wait_clickId(driver, id):
    el = WebDriverWait(driver, 10).until(EC.visibility_of_element_located((AppiumBy.ID, id)))
    if el != None:
        el.click()
        logger.log("点击" + id)


def clickText(driver, text):
    el = driver.find_element(by=AppiumBy.XPATH, value="//android.widget.TextView[@text='{}']".format(text))
    if el != None:
        el.click()
        logger.log("点击" + text)


def wait_click_text(driver, text):
    el = WebDriverWait(driver, 10).until(
        EC.visibility_of_element_located((AppiumBy.XPATH, "//android.widget.TextView[@text='{}']".format(text))))
    if el != None:
        el.click()
        logger.log("点击" + text)


def clickId(driver, id):
    el = driver.find_elements(by=AppiumBy.ID, value=id)
    if len(el) > 0:
        el[0].click()
        logger.log("点击" + id)


def swipeUp(driver, element):
    element_location = element.location
    element_x = element_location['x']
    element_y = element_location['y']
    # 执行滑动操作
    driver.swipe(element_x, element_y, element_x, element_y - 500, 500)

    logger.log("上划" + str(element))


def swipeLeft(driver, element):
    element_location = element.location
    element_x = element_location['x']
    element_y = element_location['y']
    # 执行滑动操作
    driver.swipe(element_x, element_y, element_x - 500, element_y, 500)

    logger.log("上划" + str(element))


def swipeDown(driver, element):
    element_location = element.location
    element_x = element_location['x']
    element_y = element_location['y']
    # 执行滑动操作
    driver.swipe(element_x, element_y, element_x, element_y + 500, 500)

    logger.log("下滑" + str(element))
